# -*- coding: utf-8 -*-
#*******************************************************************************
#   
#   http://www.iimanhua.com/imanhua/comic_name/ 解析器                                  
# 
#*******************************************************************************
from base import *

tag='iimanhua'

#---------------------------- 验证模块 ----------------------------

def url_judgement(url):
    if re.match(r'http://www.iimanhua.com/imanhua/\w+/',url):
        return valid_check(url)
    return False

def valid_check(url):
    print('{} catch {}'.format(tag,url))
    content=request_for(url,common_headers);
    if content:
        return get_loader(url)
    return False

def get_loader(url):
    return IimanhuaLoader(url,IimanhuaPageParser,IimanhuaVolParser)

#---------------------------- 下载器 ----------------------------

class IimanhuaLoader(ComicLoader):
    def __init__(self,url,comic_page_parser,comic_vol_parser):
        super().__init__(url,comic_page_parser,comic_vol_parser)
        self.page_encoding='gb2312'
        self.vol_encoding='gb2312'

#---------------------------- 解析器 ----------------------------

class IimanhuaPageParser(ComicPageParser):
    def __init__(self,comic):
        super().__init__(comic)
    
    def work(self,content):
        # title
        self.comic.title=re.compile(r'<h1>(.*?)</h1>').findall(content)[0]
        # description
        self.comic.description=re.compile(r'<div class="introduction" id="intro1"><p>(.*?)</p>',re.S|re.M).findall(content)[0]
        # cover
        cover_content=re.compile(r'<div class="info_cover">(.*?)</div>').findall(content)[0]
        self.comic.cover=re.compile(r'src="(.*?)"',re.S|re.M).findall(cover_content)[0]
        # vols
        urls=re.compile(r'<ul><!---->(.*?)</ul>',re.S).findall(content)[0]
        self.feed(urls)
        self.comic.vols.reverse()
        for vol in self.comic.vols:
            vol.index=self.vol_index
            self.vol_index+=1

    def handle_starttag(self,tag,attrs):
        if tag=='a':
            infos={}
            for (v,k) in attrs:
                infos[v]=k
            self.comic.vols.append('http://www.iimanhua.com'+infos['href'],infos['title'].strip())

class IimanhuaVolParser(ComicVolParser):
    def __init__(self):
        super().__init__()
    
    def work(self,content):
        en_urls=re.compile(r'var qTcms_S_m_murl_e="(.*?)";').findall(content)[0]
        urls=urls.split('$qingtiandy$')
        for url in urls:
            self.pic_urls.append((url,zero_prefix(self.pic_index)))
            self.pic_index+=1